package com.lywz.core.dao.impl;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.engine.SessionFactoryImplementor;

import com.lywz.core.dao.LYWZSession;
import com.lywz.core.dao.SessionFactory;
import com.lywz.core.dao.impl.HibernateSessionImpl;
import com.lywz.core.log.LogClerk;

/**
 * DAO层链接数据库工厂 主要工作室创建Session
 * 
 * @author Lionel pang
 * @date 2010-3-17
 * 
 * @update (openCurSession())
 * @author yangbl
 * @date 2010-4-19
 */
public class SessionFactoryImpl implements SessionFactory {
	public void closeSession(LYWZSession session) {
		session.close();
	}

	public SessionFactoryImplementor getSessionFactoryImplementor() {
		return _sessionFactoryImplementor;
	}

	public LYWZSession openCurSession() {
		LYWZSession session = _localSession.get();
		try {
			if(session == null || !session.isOpen()){
				session = openNewSession();
			}
		} catch (HibernateException e) {
			LogClerk.errLog.error("Hibernate getSession Error", e);
		}

		return session;
	}
	
	public LYWZSession openNewSession(){
		Session session = null;
		
		try {
			if (session == null || !session.isOpen()) {
				session = _sessionFactoryImplementor.openSession();
			}
		} catch (HibernateException e) {
			LogClerk.errLog.error("Hibernate getSession Error", e);
		}
		
		return new HibernateSessionImpl(session);
	}

	public void setSessionFactoryImplementor(SessionFactoryImplementor sessionFactoryImplementor) {

		_sessionFactoryImplementor = sessionFactoryImplementor;
	}
	// Hibernate Session 工厂
	private SessionFactoryImplementor _sessionFactoryImplementor;
	// 当前线程Session存储
	private final static ThreadLocal<LYWZSession> _localSession = new ThreadLocal<LYWZSession>();
}
